package network.course6;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.nio.charset.Charset;

/**
 * 服务器端的通道适配器
 */
public class ServerChannelHandlerSimple extends ChannelInboundHandlerAdapter {
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
       System.out.println("error");
       cause.printStackTrace();
       ctx.close();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        //具体处理客户端的数据信息
        System.out.println("receive message");
        ByteBuf buf=(ByteBuf)msg;
        String rev=getMessage(buf);
        System.out.println(rev);
    }

    private String getMessage(ByteBuf buf) {
        byte [] con=new byte[buf.readableBytes()];
        buf.readBytes(con);
        try {
            return new String(con, Charset.forName("UTF-8"));
        }catch (Exception e){
            System.out.println("trans byte to string error");
            e.printStackTrace();
            return null;
        }
    }
}
